package com.adminnotas;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DbAdapter {
	
	/** Variables Table Trims */
	public static final String KEY_TRIMS_ROWID = "_trimid";
	public static final String KEY_TRIMS_TITLE = "title";
	public static final String KEY_TRIMS_TYPE = "type";
	/** Variables Table COURSES */
	public static final String KEY_COURSES_ROWID = "_courseid";
	public static final String KEY_COURSES_TRIMID = "_trimid";
	public static final String KEY_COURSES_CODE = "code";
	public static final String KEY_COURSES_CREDITS = "credits";
	public static final String KEY_COURSES_NOTE = "note";
	
	
	private static final String TAG = "DbAdapter";
	private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
    
    /** Database creation sql statement */
    private static final String DATABASE_CREATE_TRIMS =
        "create table trims (_trimid integer primary key autoincrement, "
        + "title text not null, type integer not null);";
    
    private static final String DATABASE_CREATE_COURSES =
            "create table courses (_courseid integer primary key autoincrement, "
            + "_trimid integer not null, code text not null, credits integer not null, note integer not null);";

    private static final String DATABASE_NAME = "data";
    private static final String DATABASE_TABLE_TRIMS = "trims";
    private static final String DATABASE_TABLE_COURSES = "courses";
    private static final int DATABASE_VERSION = 2;

    private final Context mCtx;  //Eliminar
    
    
    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL(DATABASE_CREATE_TRIMS);
            db.execSQL(DATABASE_CREATE_COURSES);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS notes");
            onCreate(db);
        }
    }
    
    
    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public DbAdapter(Context ctx) {
        this.mCtx = ctx;
    }
    
    /**
     * Open the database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public DbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }
    
    
    /**
     * TRIMS TABLE FUNCTIONS
     */
    
    
    /**
     * Create a new trim using the title and type provided. If the trim is
     * successfully created return the new rowId for that note, otherwise return
     * a -1 to indicate failure.
     * 
     * @param title the title of the note
     * @param body the body of the note
     * @return rowId or -1 if failed
     */
    public long createTrim(String title, int type) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_TRIMS_TITLE, title);
        initialValues.put(KEY_TRIMS_TYPE, type);

        return mDb.insert(DATABASE_TABLE_TRIMS, null, initialValues);
    }

    /**
     * Delete the trim with the given rowId
     * 
     * @param rowId id of note to delete
     * @return true if deleted, false otherwise
     */
    public boolean deleteTrim(long rowId) {

        return mDb.delete(DATABASE_TABLE_TRIMS, KEY_TRIMS_ROWID + "=" + rowId, null) > 0;
    }

    /**
     * Return a Cursor over the list of all trims in the database
     * 
     * @return Cursor over all trims
     */
    public Cursor fetchAllTrims() {

        return mDb.query(DATABASE_TABLE_TRIMS, new String[] {KEY_TRIMS_ROWID, KEY_TRIMS_TITLE,
                KEY_TRIMS_TYPE}, null, null, null, null, null);
    }

    /**
     * Return a Cursor positioned at the trim that matches the given rowId
     * 
     * @param rowId id of note to retrieve
     * @return Cursor positioned to matching note, if found
     * @throws SQLException if note could not be found/retrieved
     */
    public Cursor fetchTrim(long rowId) throws SQLException {

        Cursor mCursor =

            mDb.query(true, DATABASE_TABLE_TRIMS, new String[] {KEY_TRIMS_ROWID,
                    KEY_TRIMS_TITLE, KEY_TRIMS_TYPE}, KEY_TRIMS_ROWID + "=" + rowId, null,
                    null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }

    /**
     * Update the trim using the details provided. The note to be updated is
     * specified using the rowId, and it is altered to use the title and body
     * values passed in
     * 
     * @param rowId id of trim to update
     * @param title value to set trim title to
     * @param body value to set trim body to
     * @return true if the trim was successfully updated, false otherwise
     */
    public boolean updateTrim(long rowId, String title, String type) {
        ContentValues args = new ContentValues();
        args.put(KEY_TRIMS_TITLE, title);
        args.put(KEY_TRIMS_TYPE, type);

        return mDb.update(DATABASE_TABLE_TRIMS, args, KEY_TRIMS_ROWID + "=" + rowId, null) > 0;
    }
    
    
    
    /**
     * COURSES TABLE FUNCTIONS
     */
    
    /**
     * Create a new course using the parameters provided. If the course is
     * successfully created return the new rowId for that course, otherwise return
     * a -1 to indicate failure.
     * 
     * @param trimid the trimid of the course
     * @param code the code of the course
     * @param credits the credits of the course
     * @param note the note of the course
     * @return rowId or -1 if failed
     */
    public long createCourse(long trimid, String code, int credits, int note) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_COURSES_TRIMID, trimid);
        initialValues.put(KEY_COURSES_CODE, code);
        initialValues.put(KEY_COURSES_CREDITS, credits);
        initialValues.put(KEY_COURSES_NOTE, note);

        return mDb.insert(DATABASE_TABLE_COURSES, null, initialValues);
    }

    /**
     * Delete the course with the given rowId
     * 
     * @param rowId id of course to delete
     * @return true if deleted, false otherwise
     */
    public boolean deleteCourse(long rowId) {

        return mDb.delete(DATABASE_TABLE_COURSES, KEY_COURSES_ROWID + "=" + rowId, null) > 0;
    }

    /**
     * Return a Cursor over the list of all courses that matches the given trimId
     * 
     * @param trimId id of trim courses to retrieve
     * @return Cursor to all the courses of a given trim
     * @throws SQLException if note could not be found/retrieved
     */
    public Cursor fetchCoursesByTrim (long trimId) {

        return mDb.query(true, DATABASE_TABLE_COURSES, new String[] {KEY_COURSES_ROWID, KEY_COURSES_TRIMID, KEY_COURSES_CODE,
                KEY_COURSES_CREDITS, KEY_COURSES_NOTE}, KEY_COURSES_TRIMID + "=" + trimId, null, null, null, null, null);
    }

    /**
     * Return a Cursor positioned at the course that matches the given rowId
     * 
     * @param rowId id of note to retrieve
     * @return Cursor positioned to matching note, if found
     * @throws SQLException if note could not be found/retrieved
     */
    public Cursor fetchCourse(long rowId) throws SQLException {

        Cursor mCursor =

            mDb.query(true, DATABASE_TABLE_COURSES, new String[] {KEY_COURSES_ROWID, KEY_COURSES_TRIMID, KEY_COURSES_CODE,
                    KEY_COURSES_CREDITS, KEY_COURSES_NOTE}, KEY_COURSES_ROWID + "=" + rowId, null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }

    /**
     * Update the course using the details provided. The note to be updated is
     * specified using the rowId, and it is altered to use the title and body
     * values passed in
     * 
     * @param rowId id of trim to update
     * @param trimid the trimid of the course
     * @param code the code of the course
     * @param credits the credits of the course
     * @param note the note of the course
     * @return true if the trim was successfully updated, false otherwise
     */
    public boolean updateCourse(long rowId, int trimid, String code, int credits, int note) {
        ContentValues args = new ContentValues();
        args.put(KEY_COURSES_TRIMID, trimid);
        args.put(KEY_COURSES_CODE, code);
        args.put(KEY_COURSES_CREDITS, credits);
        args.put(KEY_COURSES_NOTE, note);

        return mDb.update(DATABASE_TABLE_COURSES, args, KEY_COURSES_ROWID + "=" + rowId, null) > 0;
    }

}
